<template>
  <view class="user-manage">
    <view class="page-header">
      <view class="title-section">
        <text class="page-title">用户管理</text>
        <text class="page-subtitle">管理系统的所有用户信息</text>
      </view>
      <view class="action-section">
        <view class="search-box">
          <text class="iconfont icon-search"></text>
          <input
            type="text"
            v-model="searchKeyword"
            placeholder="搜索用户名/手机号"
            @input="handleSearch"
          />
          <text v-if="searchKeyword" class="clear-btn" @click="clearSearch"
            >×</text
          >
        </view>
        <button class="add-btn" @click="showAddUserModal = true">
          <text class="iconfont icon-add"></text>
          <text>添加用户</text>
        </button>
      </view>
    </view>

    <view class="data-card">
      <view class="card-header">
        <text class="total-count">共 {{ totalCount }} 条数据</text>
        <view class="filter-options">
          <picker
            mode="selector"
            :range="statusOptions"
            @change="handleStatusFilterChange"
            :value="statusFilterIndex"
          >
            <view class="filter-item">
              <text>状态: {{ statusOptions[statusFilterIndex] }}</text>
              <text class="iconfont icon-arrow-down"></text>
            </view>
          </picker>
          <picker
            mode="selector"
            :range="roleOptions"
            @change="handleRoleFilterChange"
            :value="roleFilterIndex"
          >
            <view class="filter-item">
              <text>角色: {{ roleOptions[roleFilterIndex] }}</text>
              <text class="iconfont icon-arrow-down"></text>
            </view>
          </picker>
        </view>
      </view>

      <view class="user-table">
        <view class="table-header">
          <view class="th username">用户名</view>
          <view class="th phone">账号</view>
          <view class="th avatar">头像</view>

          <view class="th role">角色</view>
          <view class="th status">状态</view>
          <view class="th actions">操作</view>
        </view>

        <view class="table-body">
          <view
            v-for="user in displayUserList"
            :key="user._id"
            class="table-row"
            :class="{ selected: selectedUser?._id === user._id }"
            @click="selectUser(user)"
          >
            <view class="td username">
              <view class="user-avatar">
                <text>{{ getUserInitial(user.user_name) }}</text>
              </view>
              <text>{{ user.user_name }}</text>
            </view>
            <view class="td phone">{{ user.account || "-" }}</view>
            <view class="td avatar">
              <image
                :src="user.avatar"
                style="width: 60rpx; height: 60rpx"
                mode="aspectFit"
              ></image>
            </view>

            <view class="td role">
              <view class="tag" :class="user.role === 0 ? 'admin' : 'user'">
                {{ user.role === 0 ? "管理员" : "普通用户" }}
              </view>
            </view>
            <view class="td status">
              <switch
                :checked="user.status === 1"
                @change="handleStatusChange(user)"
                @click.stop
              />
            </view>
            <view class="td actions">
              <view class="action-btn edit" @click.stop="handleEdit(user)">
                <text class="iconfont icon-edit"></text>
                <text>编辑</text>
              </view>
              <view class="action-btn reset" @click.stop="handleResetPwd(user)">
                <text class="iconfont icon-password"></text>
                <text>重置密码</text>
              </view>
              <view class="action-btn delete" @click.stop="confirmDelete(user)">
                <text class="iconfont icon-delete"></text>
                <text>删除</text>
              </view>
            </view>
          </view>

          <view v-if="displayUserList.length === 0" class="empty-data">
            <image
              class="empty-image"
              :src="url('tx', '0', 'png')"
              mode="aspectFit"
            ></image>
            <text>暂无用户数据</text>
          </view>
        </view>
      </view>

      <view class="pagination" v-if="totalPages > 1">
        <view
          class="page-btn prev"
          :class="{ disabled: currentPage === 1 }"
          @click="changePage(currentPage - 1)"
        >
          <text class="iconfont icon-left"></text>
        </view>

        <view
          v-for="page in displayedPages"
          :key="page"
          class="page-btn"
          :class="{ active: currentPage === page }"
          @click="changePage(page)"
        >
          {{ page }}
        </view>

        <view
          class="page-btn next"
          :class="{ disabled: currentPage === totalPages }"
          @click="changePage(currentPage + 1)"
        >
          <text class="iconfont icon-right"></text>
        </view>
      </view>
    </view>

    <!-- 添加/编辑用户弹窗 -->
    <uni-popup ref="userPopup" type="center">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">{{
            isEdit ? "编辑用户" : "添加用户"
          }}</text>
          <text class="close-btn" @click="handleCancel">×</text>
        </view>

        <view class="popup-body">
          <view class="form-item">
            <text class="label">账号</text>
            <input
              type="text"
              v-model="currentUser.account"
              placeholder="请输入账号"
              :disabled="isEdit"
            />
          </view>

          <view class="form-item">
            <text class="label">用户名</text>
            <input
              type="text"
              v-model="currentUser.user_name"
              placeholder="请输入用户名"
            />
          </view>

          <view class="form-item">
            <text class="label">性别</text>
            <picker
              :value="currentUser.gender"
              :range="['保密', '男', '女']"
              @change="
                (e) =>
                  (currentUser.gender = ['保密', '男', '女'][e.detail.value])
              "
            >
              <view class="picker">
                {{ currentUser.gender }}
                <text class="iconfont icon-arrow-down"></text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">邮箱</text>
            <input
              type="text"
              v-model="currentUser.email"
              placeholder="请输入邮箱"
            />
          </view>

          <view class="form-item">
            <text class="label">生日</text>
            <picker
              mode="date"
              :value="currentUser.birthday"
              @change="(e) => (currentUser.birthday = e.detail.value)"
            >
              <view class="picker">
                {{ currentUser.birthday || "请选择生日" }}
                <text class="iconfont icon-arrow-down"></text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">地区</text>
            <input
              type="text"
              v-model="currentUser.location"
              placeholder="请输入地区"
            />
          </view>

          <view class="form-item">
            <text class="label">个人简介</text>
            <textarea
              v-model="currentUser.introduction"
              placeholder="请输入个人简介"
            ></textarea>
          </view>

          <view class="form-item">
            <text class="label">积分</text>
            <input
              type="number"
              v-model="currentUser.score"
              placeholder="请输入积分"
            />
          </view>

          <view class="form-item">
            <text class="label">余额</text>
            <input
              type="number"
              v-model="currentUser.balance"
              placeholder="请输入余额"
            />
          </view>

          <view class="form-item">
            <text class="label">角色</text>
            <picker
              :value="currentUser.role"
              :range="roleOptions.slice(1)"
              @change="handleRoleChange"
            >
              <view class="picker">
                {{ roleOptions[currentUser.role + 1] }}
                <text class="iconfont icon-arrow-down"></text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">状态</text>
            <switch
              :checked="currentUser.status === 1"
              @change="handleUserStatusChange"
            />
          </view>

          <view v-if="!isEdit" class="form-item">
            <text class="label">初始密码</text>
            <input
              :type="showPassword ? 'text' : 'password'"
              v-model="currentUser.password"
              placeholder="请输入初始密码"
            />
            <text
              class="iconfont toggle-pwd"
              :class="showPassword ? 'icon-eye' : 'icon-eye-close'"
              @click="togglePasswordVisibility"
            ></text>
          </view>
        </view>

        <view class="popup-footer">
          <button class="cancel-btn" @click="handleCancel">取消</button>
          <button
            class="confirm-btn"
            @click="handleSubmit"
            :loading="submitting"
          >
            {{ isEdit ? "更新" : "添加" }}
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";

const url = $url;
const searchKeyword = ref("");
const userList = ref([]);
const totalCount = ref(0);
const showAddUserModal = ref(false);
const isEdit = ref(false);
const selectedUser = ref(null);
const submitting = ref(false);
const showPassword = ref(false);
const roleOptions = ["全部", "管理员", "普通用户"];
const statusOptions = ["全部", "启用", "禁用"];
const roleFilterIndex = ref(0);
const statusFilterIndex = ref(0);

// 分页
const pageSize = 10;
const currentPage = ref(1);
const totalPages = computed(() =>
  Math.ceil(filteredUserList.value.length / pageSize)
);

const currentUser = ref({
  username: "",
  account: "",
  password: "123456",
  gender: "保密",
  email: "",
  avatar: "https://epoch.jxksd.top/mo/images/tx4.png",
  location: "",
  introduction: "这个人很懒，还没有介绍~",
  score: 0,
  create_time: Date.now(),
  birthday: "",
  role: 1,
  default: true,
  balance: 0,
  card: Date.now(),
  coupons: [],
  addresses: [],
  activity: [],
});

const getUserInitial = (username) => {
  return username ? username.substring(0, 1).toUpperCase() : "U";
};

const clearSearch = () => {
  searchKeyword.value = "";
  handleSearch();
};

const selectUser = (user) => {
  if (selectedUser.value && selectedUser.value._id === user._id) {
    selectedUser.value = null;
  } else {
    selectedUser.value = user;
  }
};

const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

const handleUserStatusChange = (e) => {
  currentUser.value.status = e.detail.value ? 1 : 0;
};

// 过滤后的用户列表
const filteredUserList = computed(() => {
  let filtered = [...userList.value];

  // 角色过滤
  if (roleFilterIndex.value > 0) {
    filtered = filtered.filter(
      (user) => user.role === roleFilterIndex.value - 1
    );
  }

  // 状态过滤
  if (statusFilterIndex.value > 0) {
    filtered = filtered.filter(
      (user) => user.status === statusFilterIndex.value - 1
    );
  }

  return filtered;
});

// 当前页显示的用户列表
const displayUserList = computed(() => {
  const start = (currentPage.value - 1) * pageSize;
  const end = start + pageSize;
  return filteredUserList.value.slice(start, end);
});

// 显示的页码
const displayedPages = computed(() => {
  const pages = [];
  if (totalPages.value <= 7) {
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i);
    }
  } else {
    if (currentPage.value <= 3) {
      for (let i = 1; i <= 5; i++) {
        pages.push(i);
      }
      pages.push("...");
      pages.push(totalPages.value);
    } else if (currentPage.value >= totalPages.value - 2) {
      pages.push(1);
      pages.push("...");
      for (let i = totalPages.value - 4; i <= totalPages.value; i++) {
        pages.push(i);
      }
    } else {
      pages.push(1);
      pages.push("...");
      for (let i = currentPage.value - 1; i <= currentPage.value + 1; i++) {
        pages.push(i);
      }
      pages.push("...");
      pages.push(totalPages.value);
    }
  }
  return pages;
});

const handleRoleFilterChange = (e) => {
  roleFilterIndex.value = e.detail.value;
  currentPage.value = 1;
};

const handleStatusFilterChange = (e) => {
  statusFilterIndex.value = e.detail.value;
  currentPage.value = 1;
};

const changePage = (page) => {
  if (page === "..." || page < 1 || page > totalPages.value) return;
  currentPage.value = page;
};

const fetchUserList = async () => {
  try {
    const res = await uniCloud.callFunction({
      name: "alldata",
      data: {
        body: JSON.stringify({
          action: "getUserList",
          keyword: searchKeyword.value,
        }),
      },
    });

    if (res.result && res.result.code === 0) {
      userList.value = res.result.data || [];
      totalCount.value = res.result.total || userList.value.length;

      // 确保每个用户对象都有status字段
      userList.value.forEach((user) => {
        if (user.status === undefined) {
          user.status = 1; // 默认设置为启用状态
        }
      });
    } else {
      uni.showToast({
        title: res.result.message || "获取用户列表失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("获取用户列表失败:", error);
    uni.showToast({
      title: "获取用户列表失败",
      icon: "none",
    });
  }
};

const handleSearch = () => {
  currentPage.value = 1;
  fetchUserList();
};

const handleStatusChange = async (user) => {
  try {
    const res = await uniCloud.callFunction({
      name: "updateUserInfo",
      data: {
        body: JSON.stringify({
          action: "updateUser",
          account: user.account,
          status: user.status === 1 ? 0 : 1,
        }),
      },
    });

    if (res.result && res.result.status === 1) {
      uni.showToast({
        title: "状态更新成功",
        icon: "success",
      });
      fetchUserList();
    } else {
      uni.showToast({
        title: res.result.message || "更新状态失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("更新用户状态失败:", error);
    uni.showToast({
      title: "更新用户状态失败",
      icon: "none",
    });
  }
};

const handleEdit = (user) => {
  isEdit.value = true;
  currentUser.value = { ...user };
  showAddUserModal.value = true;
};

const confirmDelete = (user) => {
  uni.showModal({
    title: "确认删除",
    content: `确定要删除用户 "${user.username}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await uniCloud.callFunction({
            name: "updateUserInfo",
            data: {
              body: JSON.stringify({
                action: "deleteUser",
                account: user.account,
              }),
            },
          });

          if (result.result && result.result.status === 1) {
            uni.showToast({
              title: "删除成功",
              icon: "success",
            });
            fetchUserList();
          } else {
            uni.showToast({
              title: result.result.message || "删除失败",
              icon: "none",
            });
          }
        } catch (error) {
          console.error("删除用户失败:", error);
          uni.showToast({
            title: "删除用户失败",
            icon: "none",
          });
        }
      }
    },
  });
};

const handleResetPwd = async (user) => {
  uni.showModal({
    title: "重置密码",
    content: `确定要重置用户 "${user.username}" 的密码吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await uniCloud.callFunction({
            name: "updateUserInfo",
            data: {
              body: JSON.stringify({
                action: "resetPassword",
                account: user.account,
              }),
            },
          });

          if (result.result && result.result.status === 1) {
            uni.showToast({
              title: "密码重置成功",
              icon: "success",
            });
          } else {
            uni.showToast({
              title: result.result.message || "重置密码失败",
              icon: "none",
            });
          }
        } catch (error) {
          console.error("重置密码失败:", error);
          uni.showToast({
            title: "重置密码失败",
            icon: "none",
          });
        }
      }
    },
  });
};

const handleRoleChange = (e) => {
  currentUser.value.role = Number(e.detail.value);
};

const handleSubmit = async () => {
  if (!currentUser.value.account) {
    uni.showToast({
      title: "请输入手机号",
      icon: "none",
    });
    return;
  }

  submitting.value = true;

  try {
    const res = await uniCloud.callFunction({
      name: "updateUserInfo",
      data: {
        body: JSON.stringify({
          action: isEdit.value ? "updateUser" : "createUser",
          user_name:
            currentUser.value.username ||
            `墨枢游客${currentUser.value.account.slice(-4)}`,
          account: currentUser.value.account,
          password: currentUser.value.password,
          gender: currentUser.value.gender,
          email:
            currentUser.value.email || `${currentUser.value.account}@163.com`,
          avatar: currentUser.value.avatar,
          location: currentUser.value.location,
          introduction: currentUser.value.introduction,
          score: currentUser.value.score,
          create_time: currentUser.value.create_time,
          birthday: currentUser.value.birthday,
          role: currentUser.value.role,
          default: currentUser.value.default,
          balance: currentUser.value.balance,
          card: currentUser.value.card,
          coupons: currentUser.value.coupons,
          addresses: currentUser.value.addresses,
          activity: currentUser.value.activity,
        }),
      },
    });

    if (res.result && res.result.status === 1) {
      uni.showToast({
        title: `${isEdit.value ? "更新" : "添加"}成功`,
        icon: "success",
      });
      showAddUserModal.value = false;
      fetchUserList();
    } else {
      uni.showToast({
        title: res.result.message || `${isEdit.value ? "更新" : "添加"}失败`,
        icon: "none",
      });
    }
  } catch (error) {
    console.error(`${isEdit.value ? "更新" : "添加"}用户失败:`, error);
    uni.showToast({
      title: `${isEdit.value ? "更新" : "添加"}用户失败`,
      icon: "none",
    });
  } finally {
    submitting.value = false;
  }
};

const handleCancel = () => {
  showAddUserModal.value = false;
  currentUser.value = {
    username: "",
    account: "",
    password: "123456",
    gender: "保密",
    email: "",
    avatar: "https://epoch.jxksd.top/mo/images/tx4.png",
    location: "",
    introduction: "这个人很懒，还没有介绍~",
    score: 0,
    create_time: Date.now(),
    birthday: "",
    role: 1,
    default: true,
    balance: 0,
    card: Date.now(),
    coupons: [],
    addresses: [],
    activity: [],
  };
};

onMounted(() => {
  fetchUserList();
});
</script>

<style lang="scss" scoped>
.user-manage {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    margin-bottom: 30rpx;

    .title-section {
      margin-bottom: 20rpx;

      .page-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
        display: block;
      }

      .page-subtitle {
        font-size: 24rpx;
        color: #999;
      }
    }

    .action-section {
      display: flex;
      align-items: center;

      .search-box {
        position: relative;
        margin-right: 20rpx;

        .iconfont {
          position: absolute;
          left: 20rpx;
          top: 50%;
          transform: translateY(-50%);
          color: #999;
          font-size: 30rpx;
        }

        input {
          width: 360rpx;
          height: 80rpx;
          border: 1px solid #eee;
          border-radius: 10rpx;
          padding: 0 80rpx 0 60rpx;
          background-color: #f9f9f9;

          &:focus {
            border-color: #1890ff;
            background-color: #fff;
          }
        }

        .clear-btn {
          position: absolute;
          right: 20rpx;
          top: 50%;
          transform: translateY(-50%);
          color: #999;
          font-size: 36rpx;
          font-weight: bold;
        }
      }

      .add-btn {
        height: 80rpx;
        background-color: #1890ff;
        color: #fff;
        border-radius: 10rpx;
        font-size: 28rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 30rpx;

        .iconfont {
          margin-right: 10rpx;
          font-size: 24rpx;
        }
      }
    }
  }

  .data-card {
    background-color: #fff;
    border-radius: 15rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;

    .card-header {
      padding: 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #f0f0f0;

      .total-count {
        font-size: 26rpx;
        color: #999;
      }

      .filter-options {
        display: flex;

        .filter-item {
          margin-left: 30rpx;
          font-size: 26rpx;
          color: #666;
          display: flex;
          align-items: center;

          .iconfont {
            margin-left: 10rpx;
            font-size: 24rpx;
          }
        }
      }
    }

    .user-table {
      .table-header {
        display: flex;
        background-color: #fafafa;
        border-bottom: 1px solid #f0f0f0;

        .th {
          padding: 24rpx 20rpx;
          text-align: center;
          font-size: 28rpx;
          font-weight: 600;
          color: #333;

          &.username {
            flex: 2;
            text-align: left;
          }

          &.phone {
            flex: 2;
          }

          &.role {
            flex: 1;
          }

          &.status {
            flex: 1;
          }

          &.actions {
            flex: 3;
          }
        }
      }

      .table-body {
        .table-row {
          display: flex;
          border-bottom: 1px solid #f0f0f0;
          transition: all 0.3s;

          &:hover,
          &.selected {
            background-color: #f5f7fa;
          }

          .td {
            padding: 24rpx 20rpx;
            text-align: center;
            font-size: 28rpx;
            color: #333;
            display: flex;
            align-items: center;
            justify-content: center;

            &.username {
              flex: 2;
              justify-content: flex-start;

              .user-avatar {
                width: 60rpx;
                height: 60rpx;
                border-radius: 50%;
                background: linear-gradient(135deg, #1890ff, #36cbcb);
                color: #fff;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 24rpx;
                margin-right: 15rpx;
              }
            }

            &.phone {
              flex: 2;
            }

            &.role {
              flex: 1;

              .tag {
                display: inline-block;
                padding: 6rpx 16rpx;
                border-radius: 6rpx;
                font-size: 24rpx;

                &.admin {
                  background-color: #e6f7ff;
                  color: #1890ff;
                }

                &.user {
                  background-color: #f6ffed;
                  color: #52c41a;
                }
              }
            }

            &.status {
              flex: 1;
            }

            &.actions {
              flex: 3;
              display: flex;
              justify-content: center;

              .action-btn {
                margin: 0 10rpx;
                padding: 8rpx 16rpx;
                border-radius: 6rpx;
                font-size: 24rpx;
                display: flex;
                align-items: center;

                .iconfont {
                  margin-right: 6rpx;
                  font-size: 24rpx;
                }

                &.edit {
                  color: #1890ff;
                  background-color: #e6f7ff;
                }

                &.reset {
                  color: #faad14;
                  background-color: #fffbe6;
                }

                &.delete {
                  color: #f5222d;
                  background-color: #fff1f0;
                }
              }
            }
          }
        }

        .empty-data {
          padding: 100rpx 0;
          text-align: center;
          color: #999;
          font-size: 28rpx;

          .empty-image {
            width: 200rpx;
            height: 200rpx;
            margin-bottom: 20rpx;
          }
        }
      }
    }

    .pagination {
      display: flex;
      justify-content: center;
      padding: 30rpx 0;
      border-top: 1px solid #f0f0f0;

      .page-btn {
        min-width: 70rpx;
        height: 70rpx;
        line-height: 70rpx;
        text-align: center;
        margin: 0 10rpx;
        border-radius: 8rpx;
        font-size: 28rpx;
        color: #666;
        background-color: #f9f9f9;
        transition: all 0.3s;

        &.active {
          background-color: #1890ff;
          color: #fff;
        }

        &.disabled {
          color: #ccc;
          cursor: not-allowed;
        }
      }
    }
  }

  .popup-content {
    width: 700rpx;
    background-color: #fff;
    border-radius: 20rpx;
    overflow: hidden;

    .popup-header {
      padding: 30rpx;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .popup-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .close-btn {
        font-size: 40rpx;
        color: #999;
        cursor: pointer;
      }
    }

    .popup-body {
      padding: 30rpx;

      .form-item {
        margin-bottom: 30rpx;
        position: relative;

        .label {
          display: block;
          margin-bottom: 15rpx;
          font-size: 28rpx;
          color: #333;
        }

        input,
        .picker {
          width: 100%;
          height: 80rpx;
          border: 1px solid #eee;
          border-radius: 10rpx;
          padding: 0 20rpx;
          font-size: 28rpx;
          background-color: #fff;

          &:disabled {
            background-color: #f9f9f9;
            color: #999;
          }
        }

        .picker {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .iconfont {
            color: #999;
          }
        }

        .toggle-pwd {
          .label {
            display: block;
            margin-bottom: 10rpx;
          }

          input,
          .picker {
            width: 100%;
            height: 80rpx;
            border: 1px solid #ddd;
            border-radius: 10rpx;
            padding: 0 20rpx;
          }
        }
      }

      .btn-group {
        display: flex;
        justify-content: flex-end;
        margin-top: 30rpx;

        button {
          width: 160rpx;
          height: 80rpx;
          margin-left: 20rpx;

          &:first-child {
            background-color: #f5f5f5;
            color: #666;
          }

          &:last-child {
            background-color: #1890ff;
            color: #fff;
          }
        }
      }
    }
  }
}
</style>
